package com.peanut.baby.mvp.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseResponse;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.LiveRoom;
import com.peanut.baby.model.QA;
import com.peanut.baby.model.SearchResultBundle;
import com.peanut.baby.model.SearchResultItem;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.bbs.detail.BBSMomentDetailActivity;
import com.peanut.baby.mvp.bind.BindMobileActivity;
import com.peanut.baby.mvp.livedetail.LiveDetailActivity;
import com.peanut.baby.mvp.liveroom.LiveRoomActivity;
import com.peanut.baby.mvp.login.LoginActivity;
import com.peanut.baby.mvp.qadetail.QADetailActivity;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.peanut.devlibrary.widget.pullrecycle.PullRecyclerView;
import com.tencent.mars.xlog.Log;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by anonymouslystudio on 2017/7/20.
 */

public class SearchActivity extends BaseMvpActivity implements TitleLayout.OnTitleClickListener,
        TagFlowLayout.OnTagClickListener,
        SearchContract.View,
        TextView.OnEditorActionListener,
        TextWatcher, SearchResultAdapter.OnViewClickedListener,
        PullRecyclerView.OnRecyclerRefreshListener{
    private static final String TAG = SearchActivity.class.getSimpleName();

    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.flow_layout)
    TagFlowLayout flowLayout;
    @BindView(R.id.search_list)
    ListView searchList;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.flow_layout_history)
    TagFlowLayout flowLayoutHistory;

    @BindView(R.id.search_tags_container)
    LinearLayout searchTagsContainer;
//    @BindView(R.id.flow_layout_changyong)
//    TagFlowLayout flowLayoutFreq;

    @BindView(R.id.clearHistory)
    View clearHistory;

    @BindView(R.id.listview)
    ListView listview;

    private TagAdapter tagAdapter;
    private List<String> tags;

    private TagAdapter hisTagAdapter;
    private List<String> hisTags;

    private TagAdapter freqTagAdapter;
    private List<String> reqTags;

    private SearchPresenter presenter;

    private SearchResultAdapter adapter;
    private List<SearchResultItem> data;
    private String searchKey = "";

    private SearchResultBundle orgData;

    private HotListAdapter2 hotListAdapter;
    private List<QA> qas;

    public static void start(Context ctx) {
        ctx.startActivity(new Intent(ctx, SearchActivity.class));
    }

    public static void start(Context ctx,String defaultKey) {
        ctx.startActivity(new Intent(ctx, SearchActivity.class).putExtra("keyword",defaultKey));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        presenter = new SearchPresenter(this, this);
        if(getIntent().hasExtra("keyword")){
            searchKey = getIntent().getStringExtra("keyword");
        }
        initViews();

        if(!StringUtil.isNullOrEmpty(searchKey)){
            doSearch();
        }
    }

    private void initViews() {
        title.setTitle("搜索");
        title.setOnTitleClickedListener(this);

        searchEdit.setOnEditorActionListener(this);
        searchEdit.addTextChangedListener(this);
        searchEdit.setText(searchKey);

        tags = new ArrayList<>();
        List ss = InitManager.getInstance().getSearchKeywords();
        if(ss!=null && ss.size()>0) {
            ss.remove(0);
            tags.addAll(ss);
        }
        tagAdapter = new SearchTagAdapter(tags);
        flowLayout.setAdapter(tagAdapter);
        flowLayout.setOnTagClickListener(this);

        hisTags = new ArrayList<>();
        hisTags.addAll(SearchHistoryTool.getHistoryList());
        hisTagAdapter = new SearchTagAdapter(hisTags);
        flowLayoutHistory.setAdapter(hisTagAdapter);
        flowLayoutHistory.setOnTagClickListener(this);

        reqTags = new ArrayList<>();
        reqTags.addAll(SearchHistoryTool.getFreqTags());
        freqTagAdapter = new SearchTagAdapter(reqTags);
//        flowLayoutFreq.setAdapter(freqTagAdapter);
//        flowLayoutFreq.setOnTagClickListener(this);

        data = new ArrayList<>();
        adapter = new SearchResultAdapter(this, data);
        adapter.setOnViewClickListener(this);
        searchList.setAdapter(adapter);

        clearHistory.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                hisTags.clear();
                hisTagAdapter.notifyDataChanged();
                SearchHistoryTool.clearHistory();
            }
        });

        qas = new ArrayList<>();
        hotListAdapter = new HotListAdapter2(this, qas);
        listview.setAdapter(hotListAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                QA item = (QA)hotListAdapter.getItem(position);
                if (item.type.equals("1")) {
                    BBSMomentDetailActivity.start(view.getContext(), item.id + "");
                } else {
                    QADetailActivity.start(view.getContext(), item.id);
                }
            }
        });

        searchPageHotData();
    }


    public void searchPageHotData(){
        RetrofitClient.getInstance().searchPageHot().compose(BaseScheduler.<BaseResponse<List<QA>>>compose()).subscribe(new BaseObserver<List<QA>>() {
            @Override
            protected void onHandleSuccess(List<QA> s) {
                qas.addAll(s);
                hotListAdapter.notifyDataSetChanged();
            }

            @Override
            protected void onHandleError(String code,String msg) {

            }
        });

    }

    @Override
    public void onTitleBackClicked() {
        finish();
    }

    @Override
    public void onTitleRightClicked() {

    }

    @Override
    public void onTitleClicked() {

    }

    @Override
    public boolean onTagClick(View view, int position, FlowLayout parent) {
        Log.d(TAG, "onTagClick: " + position + " ");
        searchEdit.setText(tags.get(position));
        searchEdit.setSelection(searchEdit.getText().toString().length());
        doSearch();
        return false;
    }


    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        Log.d(TAG, "actionId: " + actionId);
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            doSearch();
            return true;
        }
        return false;
    }

    private void doSearch() {
        searchKey = searchEdit.getText().toString().trim();
        if (StringUtil.isNullOrEmpty(searchKey) || searchKey.length() <= 1) {
            showToast("请输入2个以上的搜索关键字或选择搜索类型");
            return;
        }
        SearchHistoryTool.saveHistory(searchKey);
        searchList.setVisibility(View.VISIBLE);
        searchTagsContainer.setVisibility(View.GONE);

        showProgressDialog("", false);

        presenter.search(searchKey);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s == null || s.toString().trim().length() <= 0) {
            searchList.setVisibility(View.GONE);
            searchTagsContainer.setVisibility(View.VISIBLE);
        } else {
            searchList.setVisibility(View.VISIBLE);
            searchTagsContainer.setVisibility(View.GONE);
            if (data != null && !data.isEmpty()) {
                data.clear();
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    @Override
    public void onSearchResultGet(boolean success, List<SearchResultItem> o, SearchResultBundle orgData, String failReason) {
        dismissProgressDialog();
        hideSoftKeyboard();
        this.orgData = orgData;
        if (!success) {

            showToast(failReason);
        } else {
            data.clear();
            if (o != null && !o.isEmpty()) {
                data.addAll(o);
            }
            adapter.notifyDataSetChanged();

            if (data.isEmpty()) {
                showToast("没有搜索到结果");
            }
        }
    }

    @Override
    public void onPraiseResult(boolean success, QA qa, String failReason) {
        if (!success) {
            showToast(failReason);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onJoinResult(boolean success, LiveRoom room, String failReason) {
        dismissProgressDialog();
        if (success) {
            adapter.notifyDataSetChanged();
        } else {
            showToast(failReason);
        }

    }

    @Override
    public void onPraiseClick(int position, SearchResultItem item) {
        if (InitManager.getInstance().getUser() == null) {
            LoginActivity.startForResult(SearchActivity.this);
            return;
        }
        if (StringUtil.isNullOrEmpty(InitManager.getInstance().getUser().userToken)) {
            BindMobileActivity.startForResult(SearchActivity.this);
            return;
        }
        presenter.praiseQA((QA) item.data);
    }

    @Override
    public void onJoinClick(int position, SearchResultItem item) {
        if (InitManager.getInstance().getUser() == null) {
            LoginActivity.startForResult(this);
            return;
        }

        if (InitManager.getInstance().getUser() == null) {
            LoginActivity.startForResult(this);
            return;
        }
        LiveRoom room = (LiveRoom) item.data;
        if (InitManager.getInstance().getUserId().equals(room.expertId)
                || InitManager.getInstance().getUserId().equals(room.serverId)) {
            LiveDetailActivity.start(this, room.roomId);
        } else {
            if (room.isEnroled == 0) {
                showProgressDialog("正在报名...", false);
                presenter.joinRoom(room);
            } else {
                LiveRoomActivity.start(this, room);
            }
        }
    }

    @Override
    public void onItemClick(int position, SearchResultItem item) {
        int startOffset = 0;
        if (item.type == SearchResultItem.ITEM_LIVE_MORE) {
            data.remove(position);
            for (int i = SearchPresenter.ORG_DISPLAY_SIZE; i < orgData.liveRoomList.size(); i++) {
                SearchResultItem live = new SearchResultItem();
                live.type = SearchResultItem.ITEM_LIVE;
                live.data = orgData.liveRoomList.get(i);

                data.add(position + startOffset, live);
                startOffset++;
            }
            adapter.notifyDataSetChanged();
        } else if (item.type == SearchResultItem.ITEM_QA_MORE) {
            data.remove(position);

            for (int i = SearchPresenter.ORG_DISPLAY_SIZE; i < orgData.qaList.size(); i++) {
                SearchResultItem live = new SearchResultItem();
                live.type = SearchResultItem.ITEM_QA;
                live.data = orgData.qaList.get(i);

                data.add(position + startOffset, live);

                startOffset++;
            }
            adapter.notifyDataSetChanged();
        } else if (item.type == SearchResultItem.ITEM_BBS_MORE) {
            data.remove(position);
            for (int i = SearchPresenter.ORG_DISPLAY_SIZE; i < orgData.circleList.size(); i++) {
                SearchResultItem live = new SearchResultItem();
                live.type = SearchResultItem.ITEM_BBS;
                live.data = orgData.circleList.get(i);

                data.add(position + startOffset, live);
                startOffset++;
            }
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onPullRefresh() {

    }

    @Override
    public void onLoadMore() {

    }
}
